package com.example.strategyNew.service;

import com.example.strategyNew.CfcaServiceStrategyImpl;
import com.example.strategyNew.Constants;
import com.example.strategyNew.DataPayServiceStrategyImpl;
import com.example.strategyNew.ThirdServiceStrategy;
import com.example.strategyNew.entity.BankCardAuthRequestBody;
import com.example.strategyNew.entity.BankCardAuthResponseBody;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

import static org.apache.commons.lang3.StringUtils.isBlank;

@Slf4j
public class BankCardAuthServiceImpl implements BankCardAuthService {
    // 配置规则：每组2位数字，第一位表示服务方，第二位表示是否启用
    // 例如：11,31,20
    // @Value("${bank.card.auth.ways}")
    private String rules = "11,21";

    private static ConcurrentHashMap<String, ThirdServiceStrategy> strategyMap = new ConcurrentHashMap<String, ThirdServiceStrategy>();

    static {
        strategyMap.put("1", new DataPayServiceStrategyImpl());
        strategyMap.put("2", new CfcaServiceStrategyImpl());
    }

    @Override
    public BankCardAuthResponseBody doAuth(BankCardAuthRequestBody requestBody) {
        if (isBlank(rules)) {
            return new BankCardAuthResponseBody().status("40000").message("缺少配置规则");
        }

        BankCardAuthResponseBody responseBody = null;
        String[] ruleArray = rules.split(",");
        ThirdServiceStrategy authStrategy;
        for (String rule : ruleArray) {
            if (isBlank(rule)) {
                continue;
            }
            if (rule.length() != 2) {
                log.info("配置规则错误");
                continue;
            }
            if (rule.endsWith("0")) {
                continue;
            }
            authStrategy = strategyMap.get(rule.substring(0, 1));
            responseBody = authStrategy.bankCardAuth(requestBody);
            log.info("{}返回：{}", authStrategy.getClass().toString(), responseBody);
            // 如果认证成功或失败，则返回
            if (Constants.SUCCESS.equals(responseBody.getStatus()) || Constants.FAIL.equals(responseBody.getStatus())) {
                break;
            }
            // 如果未认证或异常，则调用下一个认证服务
        }
        return responseBody;
    }

    public static void main(String[] args) {
        BankCardAuthRequestBody requestBody = new BankCardAuthRequestBody();
        requestBody.setName("test1");
        BankCardAuthResponseBody responseBody = new BankCardAuthServiceImpl().doAuth(requestBody);
        log.info("返回：{}", responseBody);
    }
}
